package com.artup.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.artup.common.Constants;
import com.artup.common.ResponseResult;
import com.artup.dao.ResourceDao;
import com.artup.dao.RoleResourceDao;
import com.artup.pojo.Resource;
import com.artup.pojo.Role;
import com.artup.pojo.RoleResource;
import com.artup.service.RoleResourceService;
import com.artup.util.CommonUtils;

@Service( value = "roleResourceService" )
@Transactional( readOnly = false )
public class RoleResourceServiceImpl implements RoleResourceService {
	private static final Logger LOGGER = LoggerFactory.getLogger(RoleResourceServiceImpl.class);
	
	@Autowired
	private RoleResourceDao roleResourceDao;
	
	@Autowired
	private ResourceDao resourceDao;

	@Override
	public ResponseResult queryRoleResourceById(long id) {
		LOGGER.info("id = " + id);
		ResponseResult response = new ResponseResult();
		
		RoleResource roleResource = null;
		try {
			roleResource = this.roleResourceDao.selectRoleResourceById(id);

			response.setStatus(Constants.ACTION_STATUS_SUCCESS);
			response.setMessage("根据【ID】查询【角色资源】  - 成功。");
			response.setData(roleResource);
		} catch (Exception e) {
			LOGGER.error("根据【ID】查询【角色资源】 - 失败！", e);
			
			response.setStatus(Constants.ACTION_STATUS_SUCCESS);
			response.setMessage("根据【ID】查询【角色资源】  - 成功。");
		}

		return response;
	}

	@Override
	public ResponseResult queryRoleResourceList(RoleResource roleResource) {
		LOGGER.info("roleResource = " + JSONArray.toJSONString(roleResource));
		
		// 1.定义返回的结果集
		ResponseResult response = new ResponseResult();
		Map<String, Object> resultMap = new HashMap<String, Object>(); // 结果集

		// 3.模糊查询【角色资源】总记录数
		long totalCount = 0;
		try {
			totalCount = this.roleResourceDao.selectRoleResourceTotalCount(roleResource);
		} catch (Exception e) {
			LOGGER.error("模糊查询【角色资源】总记录数 - 失败！", e);
		}

		resultMap.put("recordsTotal", totalCount);
		resultMap.put("recordsFiltered", totalCount);// 返回总条数

		if (0 < totalCount) {
			roleResource.setOffset( (long) roleResource.getPageIndex() ); // 设置分页的偏移量，即起始记录数

			// 4.模糊查询【角色资源】列表
			List<RoleResource> roleResourceList = null;
			try {
				roleResourceList = this.roleResourceDao.selectRoleResourceList(roleResource);
			} catch (Exception e) {
				LOGGER.error("模糊查询【角色资源】列表 - 失败！", e);

				response.setStatus(Constants.ACTION_STATUS_FAILURE);
				response.setMessage("模糊查询【角色资源】列表 - 失败！");
			}
			
			resultMap.put("data", roleResourceList);// 返回的总数据
		} else {
			resultMap.put("data", new ArrayList<RoleResource>()); // 返回的空数组
		}

		// 5.设置返回的结果集
		response.setData(resultMap);
		response.setStatus(Constants.ACTION_STATUS_SUCCESS);
		response.setMessage("模糊查询【角色资源】列表 - 成功。");

		// 6.返回结果集
		return response;
	}
	
	@Override
	public ResponseResult queryResourceListByRoleId( long roleId ) {
		LOGGER.info("roleId = " + roleId);
		
		ResponseResult response = new ResponseResult();
		
		List<Resource> resourceList = null;
		try {
			resourceList = this.resourceDao.selectValidResourceListByRoleId(roleId);
		} catch (Exception e) {
			LOGGER.error("根据【角色ID】查询有效的【资源】列表 - 失败！", e);
		}
		
		/*if(CommonUtils.isNotEmpty(resourceList)) {
			List<Resource> firstResourceList = new ArrayList<Resource>();
			List<Resource> secondResourceList = new ArrayList<Resource>();
			
			for(Resource resource : resourceList) {
				if(null == resource) {
					continue;
				}
				
				if(1 == resource.getLevel()) {
					firstResourceList.add(resource);
				} else if(2 == resource.getLevel()) {
					secondResourceList.add(resource);
				}
			}
			
			if(CommonUtils.isNotEmpty(firstResourceList)) {
				for(Resource firstResource : firstResourceList) {
					List<Resource> subResourceList = new ArrayList<Resource>();
					firstResource.setSubResourceList(subResourceList);
					
					for(Resource secondResource : secondResourceList) {
						if(null == secondResource) {
							continue;
						}
						
						if(firstResource.getId() == secondResource.getParentId()) {
							subResourceList.add(secondResource);
						}
					}
				}
			}

			response.setData(firstResourceList);
		}*/
		
		response.setData(this.setResourceLevel(resourceList));
		response.setStatus(Constants.ACTION_STATUS_SUCCESS);
		response.setMessage("根据【角色ID】查询有效的【资源】列表 - 成功。");
		
		return response;
	}
	
	@Override
	public ResponseResult queryResourceList(Resource resource, long roleId) {
		LOGGER.info("resource = " + JSONArray.toJSONString(resource) + ", roleId = " + roleId);
		
		// 1.定义返回的结果集
		ResponseResult response = new ResponseResult();
		Map<String, Object> resultMap = new HashMap<String, Object>(); // 结果集

		// 3.模糊查询【角色】总记录数
		long totalCount = 0;
		try {
			totalCount = this.resourceDao.selectResourceTotalCount(resource);
		} catch (Exception e) {
			LOGGER.error("模糊查询【角色】总记录数 - 失败！", e);
		}

		resultMap.put("recordsTotal", totalCount);
		resultMap.put("recordsFiltered", totalCount);// 返回总条数

		if (0 < totalCount) {
			resource.setOffset( (long) resource.getPageIndex() ); // 设置分页的偏移量，即起始记录数

			// 4.模糊查询【资源】列表
			List<Resource> resourceList = null;
			try {
				resourceList = this.resourceDao.selectResourceList(resource);
			} catch (Exception e) {
				LOGGER.error("模糊查询【资源】列表 - 失败！", e);
			}
			
			List<RoleResource> selectedRoleResourceList = null;
			try {
				selectedRoleResourceList = this.roleResourceDao.selectValidRoleResourceListByRoleId(roleId);
			} catch (Exception e) {
				LOGGER.error("根据【角色ID】查询【角色资源】列表 - 失败！", e);

				response.setStatus(Constants.ACTION_STATUS_FAILURE);
				response.setMessage("根据【角色ID】查询【角色资源】列表 - 失败！");
			}
			
			if(CommonUtils.isNotEmpty(resourceList)) {
				for(Resource resourceTemp : resourceList) {
					if(null == resourceTemp) {
						continue;
					}

					boolean isHaved = false;	// 是否有隶属的角色
					
					if(CommonUtils.isNotEmpty(selectedRoleResourceList)) {
						for(RoleResource resourceBelongRole : selectedRoleResourceList) {
							if(null == resourceBelongRole) {
								continue;
							}
							
							if(resourceTemp.getId() == resourceBelongRole.getRoleId()) {
								isHaved = true;
							} 
						}
					}
					
					if(isHaved) {
						resourceTemp.setIsBelong((byte) 1);
					} else {
						resourceTemp.setIsBelong((byte) 2);
					}
				}
			}
			
			resultMap.put("data", resourceList);// 返回的总数据
		} else {
			resultMap.put("data", new ArrayList<Role>()); // 返回的空数组
		}

		// 5.设置返回的结果集
		response.setData(resultMap);
		response.setStatus(Constants.ACTION_STATUS_SUCCESS);
		response.setMessage("模糊查询【角色】列表 - 成功。");

		// 6.返回结果集
		return response;
	}

	@Override
	public ResponseResult saveRoleResource(RoleResource roleResource) {
		LOGGER.info("roleResource = " + JSONObject.toJSONString(roleResource));
		
		ResponseResult response = new ResponseResult();
		
		if(null != roleResource) {
			try {
				this.roleResourceDao.insertRoleResource(roleResource);
				
				response.setStatus(Constants.ACTION_STATUS_SUCCESS);
				response.setMessage("保存【角色资源】 - 成功。");
			} catch (Exception e) {
				LOGGER.error("保存【角色资源】 - 失败！", e);
				
				response.setStatus(Constants.ACTION_STATUS_FAILURE);
				response.setMessage("保存【角色资源】 - 失败！");
			}
		}
		
		return response;
	}
	
	@Override
	public ResponseResult updateRoleResourceById(RoleResource roleResource) {
		LOGGER.info("roleResource = " + JSONObject.toJSONString(roleResource));
		ResponseResult response = new ResponseResult();
		
		if(null != roleResource) {
			try {
				this.roleResourceDao.updateRoleResourceById(roleResource);
				
				response.setStatus(Constants.ACTION_STATUS_SUCCESS);
				response.setMessage("更新【角色资源】 - 成功。");
			} catch (Exception e) {
				LOGGER.error("根据【ID】更新【角色资源】 - 失败！", e);
				
				response.setStatus(Constants.ACTION_STATUS_FAILURE);
				response.setMessage("更新【角色资源】 - 失败！");
			}
		}
		
		return response;
	}
	
	@Override
	public ResponseResult updateRoleResourceInvalidById(Long id, Long roleId) {
		LOGGER.info("id = " + id + ", roleId = " + roleId);
		ResponseResult response = new ResponseResult();
		
		try {
			this.roleResourceDao.updateRoleResourceInvalidById(id, roleId);
		} catch (Exception e) {
			LOGGER.error("根据【ID】更新【角色资源】为无效的  - 失败！", e);
			
			response.setStatus(Constants.ACTION_STATUS_FAILURE);
			response.setMessage("删除【角色】 - 失败！");
		}
		
		List<RoleResource> roleResourceList = null;
		try {
			roleResourceList = this.roleResourceDao.selectValidRoleResourceListByRoleId(roleId);
		} catch (Exception e) {
			LOGGER.error("根据【角色ID】查询有效的【角色资源】列表 - 失败！", e);
			
			response.setStatus(Constants.ACTION_STATUS_FAILURE);
			response.setMessage("更新【角色资源】 - 失败！");
		}
		
		response.setStatus(Constants.ACTION_STATUS_SUCCESS);
		response.setMessage("删除【角色资源】 - 成功。");
		response.setData(roleResourceList);
		
		return response;
	}

	@Override
	public ResponseResult updateRoleResourceByRoleId(long roleId, String resourceIds) {
		LOGGER.info("roleId = " + roleId + ", resourceIds = " + resourceIds);
		ResponseResult response = new ResponseResult();
		
		RoleResource roleResource = new RoleResource();
		roleResource.setRoleId(roleId);
		roleResource.setIsValid((byte) 2);		// 置为“无效”
		roleResource.setModifierId(1L);
		
		// 将该用户名下的全部的“角色资源”置为无效
		try {
			this.roleResourceDao.updateRoleResourceByRoleId(roleResource);
		} catch (Exception e) {
			LOGGER.error("根据【角色ID】更新【角色资源】 - 失败！", e);
			
			response.setStatus(Constants.ACTION_STATUS_FAILURE);
			response.setMessage("更新【角色资源】 - 失败！");
		}
		
		if(StringUtils.isBlank(resourceIds)) {
			response.setStatus(Constants.ACTION_STATUS_SUCCESS);
			response.setMessage("更新【角色资源】 - 成功。");
			
			return response;
		}
		
		List<RoleResource> roleResourceList_db = null;
		try {
			roleResourceList_db = this.roleResourceDao.selectRoleResourceListByRoleId(roleResource.getRoleId());
		} catch (Exception e) {
			LOGGER.error("根据【角色ID】查询【角色资源】列表 - 失败！", e);
			
			response.setStatus(Constants.ACTION_STATUS_FAILURE);
			response.setMessage("为用户分配角色 - 失败！");
		}
		
		List<RoleResource> newRoleResourceList = new ArrayList<RoleResource>();		// 新增的【角色资源】
		List<RoleResource> updateRoleResourceList = new ArrayList<RoleResource>();	// 更新的【角色资源】
		
		String resourceIds_ [] = resourceIds.split(",");
		long _resourceIds [] = new long[resourceIds_.length];	
		
		// 类型转换
		for(int index = 0; index < resourceIds_.length; index++) {
			String resourceId = resourceIds_[index];
			if(StringUtils.isBlank(resourceId)) {
				continue;
			}
			
			_resourceIds[index] = Long.parseLong(resourceIds_[index]);
			RoleResource newRoleResource = new RoleResource();
			newRoleResource.setRoleId(roleId);
			newRoleResource.setResourceId(Long.parseLong(resourceIds_[index]));
			newRoleResource.setIsValid((byte) 1);
			newRoleResource.setCreatorId(1L);
			newRoleResource.setModifierId(1L);
			newRoleResourceList.add(newRoleResource);
		}

		// 全部新增
		if(CommonUtils.isEmpty(roleResourceList_db)) {
			try {
				this.roleResourceDao.batchInsertRoleResource(newRoleResourceList);
			} catch (Exception e) {
				LOGGER.error("保存【用户-角色】 - 失败！", e);
				
				response.setStatus(Constants.ACTION_STATUS_FAILURE);
				response.setMessage("更新【角色资源】 - 失败！");
			}
		} else {	// 一部分置为“有效”，一部新增
			newRoleResourceList.clear();
			
			for(long resourceId : _resourceIds) {	// 迭代前端“资源ID”
				boolean isHaved = false;	// 是否已有此角色：true-是；false-否
				long roleResourceId_db = 0L;
				
				for(RoleResource roleResource_db : roleResourceList_db) {	// 迭代数据库“资源ID”
					if(null == roleResource_db) {
						continue;
					}
					
					if(roleResource_db.getResourceId() == resourceId) {
						isHaved = true;
						
						roleResourceId_db = roleResource_db.getId();
					}
				}
				
				if(isHaved) {	// 置为“有效”
					RoleResource updateRoleResource = new RoleResource();
					updateRoleResource.setId(roleResourceId_db);
					updateRoleResource.setIsValid((byte) 1);
					updateRoleResource.setModifierId(1L);
					
					updateRoleResourceList.add(updateRoleResource);
				} else {	// 新增
					RoleResource newRoleResource = new RoleResource();
					newRoleResource.setRoleId(roleId);
					newRoleResource.setResourceId(resourceId);
					newRoleResource.setIsValid((byte) 1);
					newRoleResource.setCreatorId(1L);
					newRoleResource.setModifierId(1L);
					
					newRoleResourceList.add(newRoleResource);
				}
			}
			
			if(CommonUtils.isNotEmpty(newRoleResourceList)) {
				try {
					this.roleResourceDao.batchInsertRoleResource(newRoleResourceList);
				} catch (Exception e) {
					LOGGER.error("批量保存【角色资源】 - 失败！", e);
					
					response.setStatus(Constants.ACTION_STATUS_FAILURE);
					response.setMessage("更新【角色资源】 - 失败！");
				}
			}
			
			if(CommonUtils.isNotEmpty(updateRoleResourceList)) {
				try {
					this.roleResourceDao.batchUpdateRoleResourceById(updateRoleResourceList);
				} catch (Exception e) {
					LOGGER.error("根据【ID】批量更新【角色资源】 - 失败！", e);
					
					response.setStatus(Constants.ACTION_STATUS_FAILURE);
					response.setMessage("更新【角色资源】 - 失败！");
				}
			}
		}
		
		/*List<RoleResource> roleResourceList = null;
		try {
			roleResourceList = this.roleResourceDao.selectValidRoleResourceListByRoleId(roleId);
		} catch (Exception e) {
			LOGGER.error("根据【角色ID】查询有效的【角色资源】列表 - 失败！", e);
			
			response.setStatus(Constants.ACTION_STATUS_FAILURE);
			response.setMessage("更新【角色资源】 - 失败！");
		}*/
		
		List<Resource> resourceList = null;
		try {
			resourceList = this.resourceDao.selectValidResourceListByRoleId(roleId);
		} catch (Exception e) {
			LOGGER.error("根据【角色ID】查询有效的【资源】列表 - 失败！", e);
		}
		
		response.setData(this.setResourceLevel(resourceList));
		response.setStatus(Constants.ACTION_STATUS_SUCCESS);
		response.setMessage("更新【角色资源】 - 成功。");
		return response;
	}

	@Override
	public ResponseResult deleteRoleResourceById(long id) {
		LOGGER.info("id = " + id);
		ResponseResult response = new ResponseResult();
		
		try {
			this.roleResourceDao.deleteRoleResourceById(id);
			
			response.setStatus(Constants.ACTION_STATUS_SUCCESS);
			response.setMessage("删除【角色资源】 - 成功。");
		} catch (Exception e) {
			LOGGER.error("根据【ID】删除【角色资源】 - 失败！", e);
			
			response.setStatus(Constants.ACTION_STATUS_FAILURE);
			response.setMessage("删除【角色资源】 - 失败！");
		}
		
		return response;
	}

	/**
	 * 设置【资源】的级别
	 * @param resourceList
	 * @return
	 */
	private List<Resource> setResourceLevel(List<Resource> resourceList) {
		if(CommonUtils.isEmpty(resourceList)) {
			return null;
		}
		
		List<Resource> firstResourceList = new ArrayList<Resource>();
		List<Resource> secondResourceList = new ArrayList<Resource>();
		
		for(Resource resource : resourceList) {
			if(null == resource) {
				continue;
			}
			
			if(1 == resource.getLevel()) {
				firstResourceList.add(resource);
			} else if(2 == resource.getLevel()) {
				secondResourceList.add(resource);
			}
		}
		
		if(CommonUtils.isNotEmpty(firstResourceList)) {
			for(Resource firstResource : firstResourceList) {
				List<Resource> subResourceList = new ArrayList<Resource>();
				firstResource.setSubResourceList(subResourceList);
				
				for(Resource secondResource : secondResourceList) {
					if(null == secondResource) {
						continue;
					}
					
					if(firstResource.getId() == secondResource.getParentId()) {
						subResourceList.add(secondResource);
					}
				}
			}
		}
		
		return firstResourceList;
	}
}